﻿// <copyright file="RatingController.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

namespace CleverCMS.Web.Cms.Admin.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using CleverCMS.Blog.Data.Entities;
    using CleverCMS.Blog.Services;

    using CleverCMS.Cms.Data.Entities;
    using CleverCMS.Cms.Services;

    [Authorize(Roles = "Admin")]
    public class RatingController : Controller
    {
        private readonly PageService        m_pageService;
        private readonly BlogEntryService   m_blogEntryService;

        public RatingController(PageService         pageService,
                                BlogEntryService    blogEntryService)
        {
            m_pageService = pageService;
            m_blogEntryService = blogEntryService;
        }

        #region Pages rating

        public ViewResult List()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ListPages(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                int count = 0;
                var allPages = m_pageService.LoadAll(null, jtStartIndex, jtPageSize, jtSorting, out count).ToList()
                        .Where(p => m_pageService.GetRating(p.Id).Any()).Select(x => new
                        {
                            Id = x.Id,
                            Title = x.PageTitle,
                            Alias = "<a href='" + Url.Action("Content", "Home", new { area = "", name = x.Alias }) + "'>" + x.Alias + "</a>",
                            Avg = GetAvgForPages(m_pageService.GetRating(x.Id).ToList()),
                            People = m_pageService.GetRating(x.Id).Count()
                        }).OrderByDescending(x => x.Avg);
                return Json(new
                {
                    Result = "OK",
                    Records = allPages,
                    TotalRecordCount = count
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        private double GetAvgForPages(List<CmsRating> ratings)
        {
            if (ratings.Any())
            {
                return ConvertDoubleToFixed(ratings.Sum(x => x.Rating) / ratings.Count());
            }
            return 0;
        }

        private string GetCategoryName(int id)
        {
            var post = m_blogEntryService.GetAll().FirstOrDefault(x => x.Id == id);
            return post != null ? post.Category.CategoryName.ToLower() : "main";
        }

        #endregion

        #region Blog posts rating

        public ViewResult ListPosts()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ListPosts(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                int count = 0;
                var allPosts = m_blogEntryService.LoadAll(jtStartIndex, jtPageSize, jtSorting, out count).ToList().ToList()
                    .Select(x => new
                    {
                        Id = x.Id,
                        Title = x.Header,
                        Alias = "<a href='" + Url.Action("Entry", "Blog", new { area = "", category = GetCategoryName(x.Id), id = x.Alias }) + "'>" + x.Alias + "</a>",
                        Avg = GetAvgForPosts(m_blogEntryService.GetRating(x.Id).ToList()),
                        People = m_blogEntryService.GetRating(x.Id).Count()
                    }).OrderByDescending(x => x.Avg);

                return Json(new { Result = "OK", Records = allPosts, TotalRecordCount = count }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        private double GetAvgForPosts(List<BlogEntryRating> posts)
        {
            if (posts.Any())
            {
                return ConvertDoubleToFixed(posts.Sum(x => x.Rating) / posts.Count());
            }
            return 0;
        }

        private static double ConvertDoubleToFixed(double from)
        {
            double cel = Math.Truncate(from);
            double ost = from - cel;
            double del = Math.Truncate(ost / 0.25);
            return cel + (del + (ost % 0.25 > 0.125 ? 1 : 0)) * 0.25;
        }

        #endregion

    }
}